package Util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;


public class HttpUtil {

    /**
     * 发送Post  x-www-form-urlencoded请求
     * response返回为GBK
     */

    public static String sendPost1(String url, Map<String, String> parameters) throws IOException {

        String postData = parameters.entrySet()
                .stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));

        String gbkResponse = "";

        // 创建URL对象
        URL requestUrl = new URL(url);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();

        // 设置请求方法为POST
        connection.setRequestMethod("POST");

        // 启用输入流和输出流
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // 设置请求头
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // 获取输出流并写入请求参数
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = postData.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取HTTP响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 获取输入流
            InputStream inputStream = connection.getInputStream();

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"GBK");

            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder responseBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }

            // 响应内容
            gbkResponse = responseBuilder.toString();

        } else {
            System.out.println("Response entity is empty.");
        }
        return gbkResponse;
    }


    /**
     * 发送Post  x-www-form-urlencoded请求
     * response返回为UTF-8
     */
    public static String sendPost2(String url, Map<String, String> parameters) throws IOException {

        String postData = parameters.entrySet()
                .stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));

        String Response = "";

        // 创建URL对象
        URL requestUrl = new URL(url);

        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();

        // 设置请求方法为POST
        connection.setRequestMethod("POST");

        // 启用输入流和输出流
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // 设置请求头
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // 获取输出流并写入请求参数
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = postData.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取HTTP响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 获取输入流
            InputStream inputStream = connection.getInputStream();

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");

            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder responseBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }

            // 响应内容
            Response = responseBuilder.toString();

        } else {
            System.out.println("Response entity is empty.");
        }
        return Response;
    }


    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     * @param params  参数(Json格式)
     */
    public static String sendJsonHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        try {
            //设置参数
            StringEntity stringEntity = new StringEntity(params, "UTF-8");
            stringEntity.setContentType("text/json");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送Post请求
     *
     * @param httpPost
     * @return
     */
    public static String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }



    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(30000)
            .setConnectTimeout(30000)
            .setConnectionRequestTimeout(30000)
            .build();




}
